import Taro from '@tarojs/taro';
import { HOST } from '@/utils/config';
import { isObject, clearNull, appendQuery, trimEnd, isHttp, trimStart, cache } from './index';
import { useRouter } from '@/hooks';

export const catchError = (result, router) => {
  if (!result.code) {
    return result.data;
  }
  if (result.code == 3005) {
    router?.push('/pages/my/login');
  }
  return Promise.reject(result);
};

export default function Http(baseURL) {
  const router = useRouter();
  baseURL = HOST.value + baseURL;
  const $http = options => {
    return new Promise((resolve, reject) => {
      let { header, method, url, params, data } = options;
      const token = cache.get('token');
      const defaultHeader = {
        Accept: 'application/json',
        Authorization: token ?? ''
      };

      if (isObject(params)) {
        url = appendQuery(url, params);
      }
      if (isObject(header)) {
        Object.assign(defaultHeader, header);
      }

      if (isHttp(baseURL) && !isHttp(url)) {
        url = `${trimEnd(baseURL, '/')}/${trimStart(url, '/')}`;
      }
      Taro.request({
        method: method,
        url: url,
        data: data,
        header: defaultHeader,
        success(response) {
          if (response.statusCode == 200) {
            resolve(response.data);
          } else {
            console.error(response);
            reject({
              code: 500,
              message: '服务器响应失败'
            });
          }
        },
        fail(err) {
          console.error(err);
          reject({
            code: 500,
            message: '服务器响应失败'
          });
        }
      });
    }).then(data => catchError(data, router));
  };

  return Object.assign($http, {
    get(url, params, config) {
      return this({
        ...config,
        url,
        method: 'get',
        params
      });
    },
    post(url, data, config) {
      clearNull(data);
      return this({
        ...config,
        url,
        method: 'post',
        data
      });
    }
  });
}
